package com.example.migrator.controller;

import com.example.migrator.batch.MigrationItemReader;
import com.example.migrator.batch.MigrationItemWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.*;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/batch")
public class BatchJobController {

    private static final Logger logger = LoggerFactory.getLogger(BatchJobController.class);

    @Autowired
    private JobLauncher jobLauncher;

    @Autowired
    private Job migrationJob;

    @Autowired
    private MigrationItemReader migrationItemReader;

    @Autowired
    private MigrationItemWriter migrationItemWriter;

    /**
     * 启动批处理数据迁移作业
     */
    @PostMapping("/run")
    public ResponseEntity<Map<String, Object>> runBatchMigration(
            @RequestParam String tableName,
            @RequestParam(required = false) String whereClause,
            @RequestParam(defaultValue = "1000") int batchSize) {

        Map<String, Object> response = new HashMap<>();

        try {
            logger.info("准备启动批处理数据迁移作业，表名: {}, 条件: {}, 批次大小: {}",
                    tableName, whereClause, batchSize);

            // 设置读取器和写入器的表名
            migrationItemReader.setTableName(tableName);
            if (whereClause != null && !whereClause.isEmpty()) {
                migrationItemReader.setWhereClause(whereClause);
            }
            migrationItemWriter.setTableName(tableName);

            // 设置作业参数
            JobParametersBuilder jobParametersBuilder = new JobParametersBuilder();
            jobParametersBuilder.addString("tableName", tableName);
            jobParametersBuilder.addLong("timestamp", System.currentTimeMillis());
            if (whereClause != null && !whereClause.isEmpty()) {
                jobParametersBuilder.addString("whereClause", whereClause);
            }
            jobParametersBuilder.addLong("batchSize", (long) batchSize);

            // 启动作业
            JobExecution jobExecution = jobLauncher.run(migrationJob, jobParametersBuilder.toJobParameters());
            JobInstance jobInstance = jobExecution.getJobInstance();

            response.put("success", true);
            response.put("message", "批处理作业启动成功");
            response.put("jobId", jobInstance.getId());
            response.put("jobName", jobInstance.getJobName());
            response.put("status", jobExecution.getStatus().name());

            logger.info("批处理作业 {} 启动成功，作业ID: {}", jobInstance.getJobName(), jobInstance.getId());
            return new ResponseEntity<>(response, HttpStatus.OK);

        } catch (Exception e) {
            logger.error("启动批处理作业时发生错误: {}", e.getMessage(), e);
            response.put("success", false);
            response.put("message", e.getMessage());
            return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 获取批处理作业状态
     */
    @GetMapping("/status/{jobExecutionId}")
    public ResponseEntity<Map<String, Object>> getJobStatus(@PathVariable Long jobExecutionId) {
        Map<String, Object> response = new HashMap<>();
        try {
            // 这里应该从JobRepository获取作业执行状态
            // 简化示例，实际应该注入JobRepository并查询
            logger.info("查询作业执行状态，作业执行ID: {}", jobExecutionId);
            
            response.put("success", true);
            response.put("message", "查询作业状态成功");
            response.put("jobExecutionId", jobExecutionId);
            response.put("status", "COMPLETED"); // 简化示例，实际应该从JobRepository获取
            
            return new ResponseEntity<>(response, HttpStatus.OK);
        } catch (Exception e) {
            logger.error("查询作业状态时发生错误: {}", e.getMessage(), e);
            response.put("success", false);
            response.put("message", e.getMessage());
            return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}